//********************************************************************************************************
// Product Name: MapWindow.dll Alpha
// Description:  The core libraries for the MapWindow 6.0 project.
//
//********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
// you may not use this file except in compliance with the License. You may obtain a copy of the License at 
// http://www.mozilla.org/MPL/ 
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF 
// ANY KIND, either expressed or implied. See the License for the specificlanguage governing rights and 
// limitations under the License. 
//
// The Original Code is MapWindow.dll for the MapWindow 6.0 project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in September, 2007.
// 
// Contributor(s): (Open source contributors should list themselves and their modifications here). 
//
//********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using MapWindow.Data;
using MapWindow.Drawing;
using MapWindow.Geometries;
using MapWindow.Main;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace MapWindow.DirectX
{
    /// <summary>
    /// A layer with drawing characteristics for LineStrings
    /// </summary>
    public class PolygonLayerDX: PolygonLayer, IPolygonLayerDX
    {
        #region Private Variables


        // The Vertex buffer stores the unmannaged Direc3D vertices that have to be updated if the symbology changes
        private VertexCollection _vertices;

        // If the structures like "border color" are to be used, a texture has to be stretched along each segment
        private TextureComponent _texture;

        // These will eventually be used to help with wide polygons
       // private IndexCollection _indices;


        // Not sure when this is changed
        //private float _scale = 1F;

        #endregion

        #region Constructors


        /// <summary>
        /// Constructor
        /// </summary>
        ///<param name="featureSet">A featureset that contains polygons</param>
        public PolygonLayerDX(IFeatureSet featureSet):base(featureSet)
        {
            Configure();
           
        }

        /// <summary>
        /// Constructor that also shows progress
        /// </summary>
        /// <param name="featureSet">A featureset that contains polygons</param>
        /// <param name="progressHandler">An IProgressHandler to recieve progress messages</param>
        public PolygonLayerDX(IFeatureSet featureSet, IProgressHandler progressHandler)
            : base(featureSet, progressHandler)
        {
            Configure();
         
        }

        /// <summary>
        /// Constructor that also shows progress
        /// </summary>
        /// <param name="featureSet">A featureset that contains polygons</param>
        /// <param name="progressHandler">An IProgressHandler to recieve progress messages</param>
        /// <param name="container">A Container to store the newly created layer in.</param>
        public PolygonLayerDX(IFeatureSet featureSet, ICollection<ILayer> container, IProgressHandler progressHandler):base(featureSet, container, progressHandler)
        {
            Configure();
          
        }

        private void Configure()
        {
           // _texture = new TextureComponent();
        }

        /// <summary>
        /// Initializes the vertex buffer (simplistic - non wide only for now)
        /// </summary>
        public virtual void Initialize(DrawArgsDX args)
        {
            IPolygonSymbolizer polygonSymbolizer = Symbolizer;
            int featureCount = DataSet.Features.Count;
          
            ProgressMeter pm = new ProgressMeter(ProgressHandler, "Building Vertex Coordinate List", featureCount);
            if (featureCount < 10000) pm.StepPercent = 50;
            if (featureCount < 5000) pm.StepPercent = 10;
            if (featureCount < 1000) pm.StepPercent = 5;

            int iFeature = 0;
            IBasicPolygon pg;
          

            // Assuming rings start and end with the same point, we have one less.
            // Since I am creating segments here, I use each point to end the previous segment and 
            // then a second time to start the next segment.  

            // Count the vertices
            
            _vertices = new PositionColoredVC(polygonSymbolizer.GetFillColor());
            _vertices.DrawBox = args.Camera.DrawBox;
          

          
            // Count the vertices
            foreach (IFeature f in DataSet.Features)
            {
                pg = f.BasicGeometry as IBasicPolygon;
                if (pg == null)
                {
                    // Multi-Linestring for this feature. (Multi-part)
                    for (int i = 0; i < f.BasicGeometry.NumGeometries; i++)
                    {
                        pg = f.BasicGeometry.GetBasicGeometryN(i) as IBasicPolygon;
                        if (pg == null) continue;
                       
                        IList<Coordinate> shell = pg.Shell.Coordinates;

                        // Shell
                        for (int iCoord = 0; iCoord < shell.Count; iCoord++)
                        {
                            if (iCoord < shell.Count - 1)
                            {
                                AddSegment(shell[iCoord], shell[iCoord + 1]);
                            }
                        }
                        

                        // Holes
                        foreach (ILinearRing interiorRing in pg.Holes)
                        {
                            IList<Coordinate> hole = interiorRing.Coordinates;
                            for (int iCoord = 0; iCoord < hole.Count; iCoord++)
                            {
                                if (iCoord < hole.Count - 1)
                                {
                                    AddSegment(hole[iCoord], hole[iCoord + 1]);
                                }
                            }
                        }


                    }
                }
                else
                {
                    pg = f.BasicGeometry as IBasicPolygon;
                    if (pg == null) continue;
                    IList<Coordinate> shell = pg.Shell.Coordinates;
    
                    // Shell
                    for (int iCoord = 0; iCoord < shell.Count; iCoord++)
                    {
                        if (iCoord < shell.Count - 1)
                        {
                            AddSegment(shell[iCoord], shell[iCoord + 1]);
                        }

                    }

                    // Holes
                    foreach (ILinearRing interiorRing in pg.Holes)
                    {
                        IList<Coordinate> hole = interiorRing.Coordinates;
                        for (int iCoord = 0; iCoord < hole.Count; iCoord++)
                        {
                            if (iCoord < hole.Count - 1)
                            {
                                AddSegment(hole[iCoord], hole[iCoord + 1]);
                            }
                        }
                    }

                }

                iFeature++;
                pm.CurrentValue = iFeature;
            }

           
            IsInitialized = true;
            pm.Reset();
        }


        private void AddSegment(Coordinate start, Coordinate end)
        {

            double sZ = start.Z;
            if (double.IsNaN(sZ)) sZ = 0;
            double eZ = end.Z;
            if (double.IsNaN(eZ)) eZ = 0;
            Vector vStart = new Vector(start.X, start.Y, sZ);
            Vector vEnd = new Vector(end.X, end.Y, eZ);
            _vertices.AddCoordinate(vStart);
            _vertices.AddCoordinate(vEnd);
            
        }

        #endregion


        #region Methods

     
      
       
        /// <summary>
        /// This is the internal drawing method that follows the standard checks.  Drawing is evoked
        /// through the Draw3D command, but internally implemented in the DrawPart method.  After
        /// the initial checks, the Draw3D method will cycle the part integer from 0 to NumParts -1.
        /// </summary>
        /// <param name="args">A DrawArgsDX class with the device and camera.</param>
        protected virtual void OnDraw(DrawArgsDX args)
        {
          

            if (_vertices.Count < 2) return;
            args.Device.RenderState.ZBufferEnable = false;

            //if (Symbolizer.IsWide) _indices.BeforeDrawing(args.Device);
            if (_texture != null) _texture.BeforeDrawing(args.Device);
            _vertices.BeforeDrawing(args.Device);
            args.Device.DrawPrimitives(PrimitiveType.LineList, 0, _vertices.Count / 2);
           // if (Symbolizer.IsWide) _indices.AfterDrawing(args.Device);
            if (_texture != null) _texture.AfterDrawing(args.Device);
            _vertices.AfterDrawing(args.Device);

        }

        #endregion

  

        #region IRenderable Members


        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (_texture != null) _texture.Dispose();
            if (_vertices != null) _vertices.Dispose();
            //if (_indices != null) _indices.Dispose();
            //if (disposing && (components != null))
            //{
            //    components.Dispose();
            //}
            base.Dispose(disposing);
        }
      

       


        

        #endregion


        // The following code region represents methods that are common between Point, Line, and Polygon layers.
        #region Common Rendering Content

        #region Events

        /// <summary>
        /// Occurs immediately before drawing, allowing it to be cancelled
        /// </summary>
        public event EventHandler<DrawVerifyArgsDX> BeforeDrawing;

        /// <summary>
        /// Occurs after drawing, indicating if an exception or cancellation occured
        /// </summary>
        public event EventHandler<DrawCompletedArgsDX> DrawingCompleted;

        /// <summary>
        /// Occurs when the data has been loaded into the model after the first drawing method
        /// </summary>
        public event EventHandler<DrawArgsDX> Inititialized;


        #endregion

        #region Private Variables

        private int _numParts = 1;
        private int _numStages = 1;
        private DrawBox _drawBox;
        private float _previousScale;
        private double _previousZ;

        #endregion

        #region Methods




        /// <summary>
        /// Causes the layer or object to draw itself to the map.  This may initiate
        /// one-time loading of buffers, but should not do heavy calculations every
        /// cycle.
        /// </summary>
        /// <param name="args">A Drawing Args structure.  This is used so that this method
        /// can also be called asynchronously</param>
        public virtual void Draw3D(DrawArgsDX args)
        {
            // try
            // {
            if (IsVisible == false)
            {
                OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
                return;
            }
            if (OnBeforeDrawing(new DrawVerifyArgsDX(args, false)))
            {
                OnDrawingCompleted(new DrawCompletedArgsDX(args, true, null));
                return;
            }

            OnDrawSetup(new DrawSetupArgs(args.Camera));
            args.Camera.Position(args.Device);

            if (IsInitialized == false)
            {
                Initialize(args);
            }




            for (int stage = 0; stage < NumStages; stage++)
            {
                for (int part = 0; part < NumParts; part++)
                {
                    DrawArgsDX innerArgs = new DrawArgsDX(args.Device, args.Camera, part, stage);
                    OnDraw(innerArgs);
                }
            }
            OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
            //}
            //catch (Exception ex)
            //{
            //    OnDrawingCompleted(this, new DrawCompletedArgsDX(args, false, ex));
            //}


        }




        /// <summary>
        /// Determines the geographic distance to use for something that is one pixel wide on the screen
        /// </summary>
        /// <param name="args">A DrawArgsDX with a Microsoft.DirectX.Device</param>
        /// <returns>A float multiplier for the scale</returns>
        public static float GetScale(DrawArgsDX args)
        {
            Viewport vp = args.Device.Viewport;
            Transforms t = args.Device.Transform;
            // Find the point along the view path of the camera that intersects with the 0 elevation of the z plane
            //Vector3 pt = Plane.IntersectLine(args.Camera.XYPlane, args.Camera.CameraPosition, args.Camera.TargetPosition);
            Vector3 pt = Vector3.Subtract(args.Camera.TargetPosition, args.Camera.CameraPosition);
            float z = Math.Abs(args.Camera.CameraPosition.Z);
            pt.X = pt.X * z / pt.Z;
            pt.Y = pt.Y * z / pt.Z;
            pt = Vector3.Add(args.Camera.CameraPosition, pt);
            pt.Z = 0;

            // Project that into screen space in order to determine where the 0-elevation plane is between the near plane an the far plane of the scene
            Vector3 depth = Vector3.Project(pt, vp, t.Projection, t.View, t.World);

            // Back project two pixels from the screen into world coordinates that are separated by a distance of 1 pixel
            Vector3 center = new Vector3((float)vp.Width / 2, (float)vp.Height / 2, depth.Z);
            Vector3 right = new Vector3(vp.Width / 2 + 1, (float)vp.Height / 2, depth.Z);
            Vector3 wCenter = Vector3.Unproject(center, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);
            Vector3 wRight = Vector3.Unproject(right, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);

            // The distance between the two locations in world coordinates gives a scale value.
            Vector3 diff = Vector3.Subtract(wRight, wCenter);

            return diff.Length();
        }



        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the draw box for this PointLayer
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DrawBox DrawBox
        {
            get { return _drawBox; }
            set { _drawBox = value; }
        }

        /// <summary>
        /// Gets the number of parts in this drawing structure
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual int NumParts
        {
            get { return _numParts; }
            protected set { _numParts = value; }
        }

        /// <summary>
        /// Gets the number of stages that will be drawn.  Each stage cycles through every part.
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual int NumStages
        {
            get { return _numStages; }
            protected set { _numStages = value; }
        }

        /// <summary>
        /// This property is computed during re-scaling.  If the ScaleMode is set to Symbolic, this
        /// will represent the scale that was used when initializing the symbols.
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual float PreviousScale
        {
            get
            {
                return _previousScale;
            }
            set
            {
                _previousScale = value;
            }
        }



        #endregion

        #region Protected Methods

        /// <summary>
        /// Copies values after properties were changed
        /// </summary>
        /// <param name="editCopy"></param>
        protected override void OnCopyProperties(object editCopy)
        {
            base.OnCopyProperties(editCopy);
            IsInitialized = false;
        }

        /// <summary>
        /// This is overridden in order to add a check to see if we need to re-scale.  This allows us
        /// to do the re-scaling check one time, instead of repeating it during each part or stage.
        /// </summary>
        /// <param name="e">A DrawVerifyArgs</param>
        /// <returns></returns>
        protected virtual bool OnBeforeDrawing(DrawVerifyArgsDX e)
        {
            float scale = GetScale(e);

            if (Symbolizer.ScaleMode == ScaleModes.Symbolic)
            {

                if (scale < _previousScale * .8 || scale > _previousScale * 1.25)
                {
                    // Zoom has changed enough to invalidate this.  Since OnBeforeDrawing is checked before Initialization, 
                    // this should invalidate the drawing when we need it.
                    base.IsInitialized = false;
                    _previousScale = scale;
                }
            }
            if (BeforeDrawing == null) return false;
            BeforeDrawing(this, e);
            return e.Cancel;
        }


        /// <summary>
        /// Fires an event when we are done with the drawing code, whether the drawing was successful, cancelled, or threw an exception.
        /// </summary>
        /// <param name="e">A DrawCompletedArgsDX parameter containing information about the drawing</param>
        protected virtual void OnDrawingCompleted(DrawCompletedArgsDX e)
        {
            if (DrawingCompleted == null) return;
            DrawingCompleted(this, e);
        }

        /// <summary>
        /// Ensures that if the mode is symbolic, the initialization code will occur every time.
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnDrawSetup(DrawSetupArgs e)
        {
            if (_drawBox == null || e.Camera.DrawBox.Equals(_drawBox) == false)
            {
                IsInitialized = false;
                _drawBox = e.Camera.DrawBox;
            }

            if (Symbolizer.ScaleMode == ScaleModes.Symbolic)
            {
                double z = e.Camera.CameraLocation.Z;
                if (z > _previousZ * 2 || z < _previousZ / 2)
                {
                    base.IsInitialized = false;
                    _previousZ = z;
                }

            }
        }




        /// <summary>
        /// Fires the Initialized event
        /// </summary>
        /// <param name="e">An EventArgs parameter</param>
        protected virtual void OnInitialize(DrawArgsDX e)
        {
            IsInitialized = true;
            if (Inititialized != null)
            {
                Inititialized(this, e);
            }

        }



        #endregion

        #endregion


    }
}
